/*
 * @Author       : 乐乐侠在此
 * @Date         : 2024-02-19 14:24:20
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2024-02-19 16:04:15
 * @Description  : 请填写简介
 */
#ifndef __TASK__
#define __TASK__
#include <iostream>
#include <thread>
#include <string>
#include <mutex>

using namespace std;
timed_mutex mtx1, mtx2;
void func1()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    cout << "thread1 is started" << endl;
    unique_lock<timed_mutex> u_mtx1(mtx1, defer_lock);
    unique_lock<timed_mutex> u_mtx2(mtx2, defer_lock);
    if (u_mtx1.try_lock_for(std::chrono::seconds(1)))
    {
        u_mtx2.try_lock_for(std::chrono::seconds(1));
        cout << "thread1 is running" << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(2000));
        u_mtx1.unlock();
        u_mtx2.unlock();
    }

    /* mtx1.lock();
    mtx2.lock();

    mtx1.unlock();
    mtx2.unlock(); */
}
void func2()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    cout << "thread2 is started" << endl;

    unique_lock<timed_mutex> u_mtx2(mtx2, defer_lock);
    unique_lock<timed_mutex> u_mtx1(mtx1, defer_lock);
    if (u_mtx2.try_lock_for(std::chrono::seconds(1)))
    {
        u_mtx1.try_lock_for(std::chrono::seconds(1));
        cout << "thread1 is running" << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(2000));
         u_mtx1.unlock();
        u_mtx2.unlock();
    }
    /* mtx2.lock();
    mtx1.lock();

    mtx1.unlock();
    mtx2.unlock(); */
}
int main()
{
    int a = 0;
    cout << "a: " << a << endl;
    thread m_thread2(func1);
    thread m_thread1(func2);

    m_thread1.join();
    m_thread2.join();
    cout << "over" << endl;
    // cout << "a: " << a << endl;
}
#endif